package com.keya.features.gateway;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.keya.config.JobConfig;
import com.keya.mapper.DicomTaskMapper;
import com.keya.device.GatewayProperties;
import com.keya.dicomtask.DicomTask;
import com.keya.utils.LogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;



@Configuration
@Slf4j
public class ClearDicom implements SchedulingConfigurer {

    @Resource
    JobConfig jobConfig;
    @Resource
    DicomTaskMapper dicomTaskMapper;
    @Resource
    GatewayProperties gateWayProperties;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                this::job,
                triggerContext -> new CronTrigger(jobConfig.getClearData()).nextExecutionTime(triggerContext)
        );
    }

    public void job() {
        log.info("开始处理前一天未匹配到的数据。");
        LocalDateTime oneDayAgo = LocalDateTime.now().minusDays(gateWayProperties.getClearData());
        LambdaQueryWrapper<DicomTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DicomTask::getMark, 0)
                .lt(DicomTask::getCreatedAt, oneDayAgo)
                .orderByAsc(DicomTask::getCreatedAt);
        List<DicomTask> dicomTasks = dicomTaskMapper.selectList(wrapper);
        if (ObjectUtil.isNotEmpty(dicomTasks)) {
            for (DicomTask dicomTask : dicomTasks) {
                LogUtils.info(dicomTask.getId(), "被清理");
                dicomTask.setMark(2);
                dicomTaskMapper.updateById(dicomTask);
                LogUtils.info(dicomTask.getPath(), "被清理");
                FileUtil.del(dicomTask.getPath());
            }
        }
    }

}
